﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class ItemsManager : MonoBehaviour {
    //字典用来存放实例化的对象
    public static Dictionary<int, BaseItems> dicAdd;
    public GameObject[] items;
    GameObject item;

    Image imageSource;
    Text indexText;
    int index = 0;
	void Awake () {
        Load();
	}
	
	// Update is called once per frame
	void Update () {
        //按Q键添加物品
		if(Input.GetKeyDown (KeyCode.Q))
        {
            int index = Random.Range(0, 4);
            ItemsAdd(dicAdd[index]);
        }
	}
    void Load()
    {
        dicAdd = new Dictionary<int, BaseItems>();
        ArmorItems a1 = new ArmorItems(0, 1000, 900, "防护甲", "穿戴后可抵挡部分伤害", "Picture/icon01", 999);
        ConsumableItems c1 = new ConsumableItems(1, 300, 200, "玉露丸", "使用后可恢复部分血量", "Picture/icon02", 0, 200);
        WeaponItems w1 = new WeaponItems(2, 2000, 1600, "乾坤刀", "可对敌方英雄造成10%伤害", "Picture/icon04", 1000f);
        InspectorItems i1 = new InspectorItems(3, 200, 0, "惊喜礼盒", "随机赠送礼物", "Picture/icon03", "此物品不可出售");
        dicAdd.Add(a1.ID, a1);
        dicAdd.Add(c1.ID, c1);
        dicAdd.Add(w1.ID, w1);
        dicAdd.Add(i1.ID, i1);
    }
    //添加物品
    void ItemsAdd(BaseItems baseItems)
    {
        //实例化物品
        item = GameObject.Instantiate(Resources.Load("Prefabs/Item")) as GameObject;
        imageSource = item.GetComponent<Image>();
        imageSource.overrideSprite = Resources.Load(baseItems.Icon, typeof(Sprite)) as Sprite;
        bool isFind = false;
        for (int i = 0; i < items.Length; i++)
        {
            if(items[i].transform.childCount>0)
            {
                if(imageSource .overrideSprite.name==items [i].transform .GetChild(0).transform .GetComponent<Image>().overrideSprite .name )
                {
                    isFind = true;
                    indexText = items[i].transform.GetChild(0).transform.GetChild(0).GetComponent<Text>();
                    index = int.Parse(indexText.text);
                    index++;
                    indexText.text = index.ToString();
                }
            }
        }
        //判断物品栏中的自物体是否为空
        if(isFind==false)
        {
            for (int i = 0; i < items.Length; i++)
            {
                if (items[i].transform.childCount == 0)
                {
                    item.transform.parent = items[i].transform;
                    item.transform.localPosition = Vector3.zero;
                    break;
                }
            }
        }
          
    }
}
